package com.sdkj.fixed.asset.system.controller;



import cn.hutool.core.util.StrUtil;
import com.sdkj.fixed.asset.api.login.pojo.LoginRole;
import com.sdkj.fixed.asset.api.login.pojo.LoginUser;
import com.sdkj.fixed.asset.api.system.OrgApi;
import com.sdkj.fixed.asset.api.system.in_vo.EditState;
import com.sdkj.fixed.asset.common.base.*;
import com.sdkj.fixed.asset.common.core.RoleType;
import com.sdkj.fixed.asset.common.exception.LogicException;
import com.sdkj.fixed.asset.common.utils.FileDownload;
import com.sdkj.fixed.asset.pojo.system.OrgManagement;
import com.sdkj.fixed.asset.pojo.system.group.IdMustOrg;
import com.sdkj.fixed.asset.pojo.system.group.OrgEdit;
import com.sdkj.fixed.asset.system.service.OrgService;
import com.sdkj.fixed.asset.system.util.CacheUtil;
import org.apache.ibatis.io.Resources;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName OrgController
 * @Description TODO
 * @Author 张欣
 * @Date 2020/7/20 14:38
 */
@Controller
public class OrgController extends BaseController<OrgManagement> implements OrgApi {
    @Autowired
    private OrgService orgService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private CacheUtil cacheUtil;
    @Override
    public BaseService getService() {
        return orgService;
    }

    /**
     * 新增组织架构
     * @param orgManagement
     * @return
     * @throws Exception
     */
    @Override
    public BaseResultVo insertSimple(@RequestBody @Validated  OrgManagement orgManagement) throws Exception{
        String token = request.getHeader("token");
        List<String> roles = cacheUtil.getUserRole(token);
        String userId = cacheUtil.getUserId(token);
        orgManagement.setCuser(userId);
        orgManagement.setEuser(userId);
        if(orgManagement.getType() == 1){
            if(roles.contains(RoleType.SYSADMIN.getRoleType()) && StrUtil.isNotBlank(orgManagement.getPid()) ){
                throw new LogicException("超级管理员只能新增根节点");
            }
        }

        if((!roles.contains(RoleType.SYSADMIN.getRoleType())) && StrUtil.isBlank(orgManagement.getPid())){
            throw new LogicException("不能新增根节点");
        }
        String userCompanyId = "";
        if(!roles.contains(RoleType.SYSADMIN.getRoleType())) {
            userCompanyId = cacheUtil.getUserCompanyId(token);
        }
        orgService.addOrg(orgManagement,userCompanyId);

        return BaseResultVo.success("",orgManagement.getId());
    }
    /**
     * 修改组织架构
     * @param orgManagement
     * @return
     * @throws Exception
     */
    @Override
    public BaseResultVo updateById(@RequestBody @Validated(OrgEdit.class)  OrgManagement orgManagement) throws Exception{
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtil.getUser(token);
        orgManagement.setEuser(loginUser.getUserId());
        List<LoginRole> loginRoles = loginUser.getLoginRoles();
        List<String> roles = loginRoles.stream().map(LoginRole::getRoleLevel).collect(Collectors.toList());
        if(roles.contains(RoleType.SYSADMIN.getRoleType()) && StrUtil.isNotBlank(orgManagement.getPid())){
            throw new LogicException("超级管理员只能修改根节点");
        }
        orgService.editOrg(orgManagement,loginUser.getCompanys().get(0).getCompanyId());
        return BaseResultVo.success("",orgManagement.getId());
    }

    /**
     * 禁用或启用
     * @param orgManagement
     * @return
     */
    @Override
    public BaseResultVo forbiddenOrOrgEnable( @Validated EditState orgManagement){
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtil.getUser(token);
        orgService.forbiddenOrOrgEnable(orgManagement,loginUser.getUserId());
        return BaseResultVo.success("",orgManagement.getId());
    }

    /**
     * 查看机构详情
     * @param orgManagement
     * @return
     * @throws Exception
     */
    @Override
    public BaseResultVo queryOrgInfo(@Validated(IdMustOrg.class) OrgManagement orgManagement) throws Exception{
        OrgManagement org = orgService.selectByPrimaryKey(orgManagement.getId());
        if(org != null){
            if(org.getPid().equals("NONE")){
                org.setpName("");
            }else{
                org.setpName(orgService.selectByPrimaryKey(org.getPid()).getName());
            }
        }
        return  BaseResultVo.success(org);
    }
    /**
     * 查询所有机构
     * @return
     * @throws Exception
     */
    @Override
    public BaseResultVo getAllOrg() throws Exception{
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtil.getUser(token);
        List<LoginRole> loginRoles = loginUser.getLoginRoles();
        List<String> roles = loginRoles.stream().map(LoginRole::getRoleLevel).collect(Collectors.toList());
        boolean flag = roles.contains(RoleType.SYSADMIN.getRoleType());
        String companyId = "";
        if(!flag){
             companyId = loginUser.getCompanys().get(0).getCompanyId();
        }
        List<OrgManagement> allOrg = orgService.getAllOrg(companyId, flag,false);
        return BaseResultVo.success(allOrg);

    }
    /**
     * 获取所有启用状态的组织架构
     * @return
     * @throws Exception
     */
    @Override
    public BaseResultVo getAllEnableOrg() throws Exception {
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtil.getUser(token);
        List<LoginRole> loginRoles = loginUser.getLoginRoles();
        List<String> roles = loginRoles.stream().map(LoginRole::getRoleLevel).collect(Collectors.toList());
        boolean flag = roles.contains(RoleType.SYSADMIN.getRoleType());
        List<OrgManagement> allOrg = orgService.getAllOrg(loginUser.getCompanys().get(0).getCompanyId(), flag,true);
        return BaseResultVo.success(allOrg);
    }
     /**
     *获取当前登录用户权限下启用状态的公司
     * @return
     * @throws Exception
     */
    @Override
    public BaseResultVo getAuthEnableCompany() throws Exception{
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtil.getUser(token);
        List<LoginRole> loginRoles = loginUser.getLoginRoles();
        List<String> roles = loginRoles.stream().map(LoginRole::getRoleLevel).collect(Collectors.toList());
        boolean flag =roles.contains(RoleType.SYSADMIN.getRoleType());
        if(loginUser.getCompanys().size() == 0){
            throw new LogicException("请确认当前登录用户公司");
        }
        List<OrgManagement> allOrg = orgService.getAuthEnableCompany(loginUser.getCompanys().get(0).getCompanyId(), flag,loginUser.getUserId());
        return BaseResultVo.success(allOrg);
    }
    @Override
    public BaseResultVo getAuthOrg() throws Exception{
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtil.getUser(token);
        List<LoginRole> loginRoles = loginUser.getLoginRoles();
        List<String> roles = loginRoles.stream().map(LoginRole::getRoleLevel).collect(Collectors.toList());
        boolean flag =roles.contains(RoleType.SYSADMIN.getRoleType());
        if(loginUser.getCompanys().size() == 0){
            throw new LogicException("请确认当前登录用户公司");
        }
        List<OrgManagement> allOrg = orgService.getAuthOrg(loginUser.getCompanys().get(0).getCompanyId(), flag,loginUser.getUserId());
        return BaseResultVo.success(allOrg);
    }
    /**
     *获取启用状态的公司
     * @return
     * @throws Exception
     */
    @Override
    public BaseResultVo getEnableCompany() throws Exception{
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtil.getUser(token);
        List<LoginRole> loginRoles = loginUser.getLoginRoles();
        List<String> roles = loginRoles.stream().map(LoginRole::getRoleLevel).collect(Collectors.toList());
        boolean flag =roles.contains(RoleType.SYSADMIN.getRoleType());

        List<OrgManagement> allOrg = orgService.getEnableCompany(loginUser.getCompanys().get(0).getCompanyId(), flag);
        return BaseResultVo.success(allOrg);
    }
    /**
     * 获取公司下启用状态的部门
     * @return
     * @throws Exception
     */
    @Override
    public BaseResultVo getEnableDeptByCompanyId(@Validated(IdMustOrg.class) OrgManagement orgManagement) throws Exception{
        List<OrgManagement> depts = orgService.getEnableDeptByCompanyId(orgManagement.getId());
        return BaseResultVo.success(depts);
    }
    /**
     * 获取当前登录用户权限下公司下启用状态的部门
     * @return
     * @throws Exception
     */
    @Override
    public BaseResultVo getAuthEnableDeptByCompanyId(@RequestBody OrgManagement orgManagement) throws Exception{
        List<OrgManagement> depts = orgService.getAuthEnableDeptByCompanyId(orgManagement.getId(),cacheUtil.getUserId(request.getHeader("token")));
        return BaseResultVo.success(depts);
    }
    @Override
    public void downDeptTemp(HttpServletResponse response) throws Exception {
        FileDownload.fileDownload(response,request,getClass().getResource("/").getPath()+"/template/组织结构-部门导入模板.xlsx","组织结构-部门导入模板.xlsx");
    }
    @Override
    public void downCompanyTemp(HttpServletResponse response) throws Exception{
        FileDownload.fileDownload(response,request,getClass().getResource("/").getPath()+"/template/组织结构-公司导入模板.xlsx","组织结构-公司导入模板.xlsx");

    }

    /**
     * 导入公司
     * @param file
     * @return
     * @throws Exception
     */
    @Override
    public BaseResultVo importOrg(MultipartFile file) throws Exception {
        if(file == null){
            throw  new LogicException("文件不能为空");
        }
        if(!file.getOriginalFilename().endsWith(".xlsx")){
            throw  new LogicException("文件类型必须为【.xlsx】");
        }
        if(file.getSize() > 10*1024*1024){
            throw  new LogicException("文件最大允许10MB");
        }
        orgService.insertImportOrg(file,cacheUtil.getUser(request.getHeader("token")));
        return BaseResultVo.success();
    }
    /**
     * 导入部门
     * @param file
     * @return
     */
    @Override
    public BaseResultVo importDept(MultipartFile file) throws Exception {
        if(file == null){
            throw  new LogicException("文件不能为空");
        }
        if(!file.getOriginalFilename().endsWith(".xlsx")){
            throw  new LogicException("文件类型必须为【.xlsx】");
        }
        if(file.getSize() > 10*1024*1024){
            throw  new LogicException("文件最大允许10MB");
        }
        orgService.insertImportDept(file,cacheUtil.getUser(request.getHeader("token")));
        return BaseResultVo.success();
    }
}
